const path = require('path')
const Koa = require('koa')
const Router = require('@koa/router')
const { koaBody } = require('koa-body')
const cors = require('@koa/cors')
const static = require('koa-static')
const mount = require('koa-mount')
const multer = require('@koa/multer')
const morgan = require('morgan')
const PORT = 8000

const app = new Koa()
const router = new Router()

const UPLOAD_DIR = path.join(__dirname, '/uploads')
const RESOURCE_URL = `http://localhost:${PORT}`
const storage = multer.diskStorage({
  destination: async function (req, file, cb) {
    // 设置文件的存储目录
    cb(null, UPLOAD_DIR)
  },
  filename: function (req, file, cb) {
    // 设置文件名
    cb(null, `${file.originalname}`)
  },
})
const multerUpload = multer({ storage })

// 将 morgan 转换为 Koa 中间件
app.use(async (ctx, next) => {
  //   morgan('combined')(ctx.req, ctx.res, next)
  morgan('tiny')(ctx.req, ctx.res, next)
})

// 解决跨域
app.use(cors())

// 托管静态资源
app.use(static(UPLOAD_DIR))

// 托管静态资源: 设置虚拟路径'/static'映射到实际的'public'目录
app.use(mount('/static', static(path.join(__dirname, 'uploads'))))

// 获取post请求体参数
app.use(koaBody())
app.use((ctx, next) => {
  console.log('中间件')
  next()
})

router.get('/', (ctx) => {
  ctx.body = 'hello world'
})

router.get(
  '/a',
  (ctx, next) => {
    console.log('before')
    next()
  },
  (ctx) => {
    console.log(ctx.query) // 获取查询字符串
    ctx.body = 'hello a'
  }
)
router.get('/b/:id', (ctx) => {
  console.log(ctx.params) // 获取路由参数
  ctx.body = 'hello b'
})

router.post('/login', (ctx) => {
  console.log(ctx.request.body) // 获取post请求体参数，ctx.body不行哦
  ctx.body = '登录成功'
})

// 上传文件
router.post(
  '/upload/single',
  async (ctx, next) => {
    try {
      await next()
      ctx.body = {
        code: 1,
        msg: '文件上传成功',
        url: `${RESOURCE_URL}/${ctx.file.originalname}`,
      }
    } catch (error) {
      ctx.body = {
        code: 0,
        msg: '文件上传失败',
      }
    }
  },
  multerUpload.single('avatar')
)

app.use(router.routes()).use(router.allowedMethods())

app.listen(8000)
